//
//  DetailBanner.swift
//  shop
//
//  Created by chen on 2025/5/14.
//

import SwiftUI
import Kingfisher

struct DetailBanner: View {
    
    @ObservedObject var vm: DetailViewModel
    
    @State private var selectedTab = 0
    
    var body: some View {
        VStack(spacing: 0){
            // 图片索引
            Spacer()
            
            HStack(spacing: 0) {
                Spacer()
                
                Text("\(selectedTab + 1)/\(vm.bannerList.count)")
                    .font(.system(size: 14))
                    .foregroundStyle(.white)
                    .padding(.vertical, 2)
                    .padding(.horizontal, 8)
                    .background(Color.black.opacity(0.25))
                    .cornerRadius(5)
            }
            .padding(.trailing, 20)
            .padding(.bottom, 15)
            
        }
        .frame(width: UIScreen.main.bounds.width, height: 350)
        .background(
            // 背景图
            KFImage.url(URL(string: vm.bannerList.isEmpty ? "" : vm.bannerList[selectedTab]))
                   .loadDiskFileSynchronously()
                   .cacheMemoryOnly()
                   .fade(duration: 0.35)
                   .resizable()
                   .frame(width: UIScreen.main.bounds.width, height: 350)
        )
        .gesture(
            DragGesture(minimumDistance: 50)
                .onEnded { value in
                    withAnimation {
                        if value.translation.width < 0 && selectedTab < vm.bannerList.count - 1 {
                            withAnimation {
                                selectedTab += 1
                            }
                        } else if value.translation.width > 0 && selectedTab > 0 {
                            withAnimation {
                                selectedTab -= 1
                            }
                        }
                    }
                }
        )
    }
}

#Preview {
    ZStack{
        Color.gray.opacity(0.2)
            .ignoresSafeArea()
        
        VStack(spacing: 0){
            ScrollView{
                DetailBanner(vm: DetailViewModel.shared)
                Text("sdsd")
            }
        }
    }
}
